package com.itcam.interview.pro04thread;

import lombok.Getter;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author : Cammy.Wu
 * Description : 
 */

public class ThreadLocalDemo04Shutdown {

    /**
     * 线程执行的任务
     */
    static class Task implements Runnable {
        @Getter
        String name = "";

        public Task(int i) {
            name = "task-" + i;
        }

        @Override
        public void run() {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println("sleep completed, " + getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("interrupted, " + getName());
                return;
            }
            System.out.println(getName() + " finished");
            System.out.println();
        }
    }

    public static void main(String[] args) {
//        shutdown_demo();
        shutdownNow_demo();
    }

    /*
        第六个任务开始及之后的任务都被拒绝，1~5号任务正常执行。
        所以shutdown方法将线程池状态置为shutdown，线程池不会立即执行，
        要等正在执行和队列里等待的任务执行完才会停止。
     */
    private static void shutdown_demo() {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        // 提交10个任务，再第5个任务提交完，准备提交第6个的时候执行shutdown
        for (int i = 1; i <= 10; i++) {
            System.out.println("第" + i + "次提交");
            threadPool.execute(new Task(i));
            if (i == 5) {
                threadPool.shutdown();
            }
        }
        System.out.println(Thread.currentThread().getName() + "大哥，还有我呢~~~");
    }

    /**
     * 调用 shutdownNow 后，第一个任务正在睡眠的时候，触发了 interrupt 中断，
     * 之前等待的任务2-5被从队列中清除并返回，之后的任务6~10被拒绝
     * but
     * shutdownNow 方法将线程池状态置为 STOP，试图让线程池立刻停止，
     * 但不一定能保证立即停止，要等所有正在执行的任务（不能被 interrupt 中断的任务）执行完才能停止
     */
    private static void shutdownNow_demo() {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        for (int i = 1; i <= 10; i++) {
            try {
                System.out.println("第" + i + "次提交");
                threadPool.execute(new Task(i));
            } catch (Exception e) {
                System.out.println("rejected, task-" + i);
            }
            if (i == 5) {
                List<Runnable> runnables = threadPool.shutdownNow();
                for (Runnable runnable : runnables) {
                    if(runnable instanceof Task){
                        System.out.println("waiting task: " + ((Task) runnable).getName());
                    }
                }
            }
        }
    }

}
